<template>
  <el-table-column class-name="order-table-col">
    <template #header>
      <div class="flex items-center" style="width: 100%">
        <div class="flex justify-center" style="flex: 3">
          商品信息
        </div>
        <div class="flex justify-center" style="flex: 1">
          收货人
        </div>
        <div class="flex justify-center" style="flex: 1">
          实付金额(元)
        </div>
        <div class="flex justify-center" style="flex: 1.5">
          买家留言
        </div>
        <div class="flex justify-center" style="flex: 0.8">
          操作
        </div>
      </div>
    </template>
    <template #default="scope">
      <el-table
        :ref="setOrderTableRef"
        :border="true"
        :data="scope.row.goodsInfoList"
        :header-cell-style="headerStyle"
        :span-method="spanMethod"
        style="width: 100%"
        :key="scope.row.orderSn"
      >
        <el-table-column prop="spuName" min-width="40%">
          <template #header>
            <div
              class="mr-[20px] h-[35px] flex items-center pl-[10px] pr-[30px] justify-between"
              style="background-color: var(--app-content-bg-color)"
            >
              <div>
                <span class="mr-20px">订单号：{{ scope.row.orderSn }} </span>
                <span class="mr-20px">{{ formatDate(scope.row.settledTime) }}</span>
                <span>状态：{{OrderStatusEnumName[OrderStatusEnum[scope.row.orderStatus ]] }}</span>
              </div>
              <div>
                提成佣金：<span class="text-red-500"
                  >￥{{ floatToFixed2(scope.row.realMoney) }}
                </span>
                <span class="text-red-500"
                  >(佣金类型：{{ CommissionTypeName[CommissionType[scope.row.shareBenefitType]] }})
                </span>
              </div>
            </div>
          </template>
          <template #default="{ row }">
            <div class="flex flex-wrap">
              <div class="mb-[10px] mr-[10px] flex items-start">
                <div class="mr-[10px]">
                  <el-image
                    :src="row.picUrl"
                    class="!h-[45px] !w-[45px]"
                    fit="contain"
                    @click="imagePreview(row.picUrl)"
                  >
                    <template #error>
                      <div class="image-slot">
                        <icon icon="ep:picture" />
                      </div>
                    </template>
                  </el-image>
                </div>
                <ElTooltip :content="row.spuName" placement="top">
                  <span class="overflow-ellipsis max-h-[45px] overflow-hidden">
                    {{ row.spuName }}
                  </span>
                </ElTooltip>
                <div class="flex">
                  <div class="mr-[10px]">
                    <span class="text-gray-500">数量：</span>
                    <span>{{ row.count }}</span>
                  </div>
                  <div>
                    <span class="text-gray-500">价格：</span>
                    <span>￥{{ floatToFixed2(row.price) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收货人" min-width="13%">
          <template #default>
            <div>
              <div>{{ scope.row.receiverName || '--' }}</div>
              <div>{{ scope.row.receiverMobile || '--' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实付金额" min-width="13%">
          <template #default>
            ￥{{ floatToFixed2( scope.row.orderAmount) }}
            <div class="text-gray-500 text-12px">(含运费￥{{floatToFixed2(scope.row.deliveryPrice)  }})</div>
          </template>
        </el-table-column>
        <el-table-column label="买家留言" min-width="20%">
          <template #default>
            <div>
              {{ scope.row.userRemark || scope.row.remark || '--' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" min-width="10%">
          <template #default>
            <slot :row="scope.row"></slot>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </el-table-column>
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { DeliveryTypeEnum } from '@/utils/constants'
import { formatDate } from '@/utils/formatTime'
import { floatToFixed2 } from '@/utils'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { OrderVO } from '@/api/mall/trade/order'
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import type { DeliveryPickUpStoreVO } from '@/api/mall/trade/delivery/pickUpStore/index'
import { watch } from 'vue'

defineOptions({ name: 'OrderTableColumn' })

const props = defineProps<{
  list: OrderVO[]
  // pickUpStoreList: DeliveryPickUpStoreVO[]
}>()

// 监听list变化，确保组件能够响应数据变化
watch(() => props.list, (newVal) => {
  // 数据变化时，组件会自动重新渲染
  console.log('订单列表数据已更新', newVal.length)
}, { deep: true })

const headerStyle = ({ row, columnIndex }: { row: any; rowIndex: number; column: TableColumnCtx<any>; columnIndex: number }): any => {
  // 表头第一行第一列占 8
  if (columnIndex === 0) {
    row[columnIndex].colSpan = 8
  } else {
    // 其余的不要
    row[columnIndex].colSpan = 0
    return {
      display: 'none'
    }
  }
}
// purchase_order_payment：采购订单分佣 shop_order_payment：商城订单分佣 shop_rebate_refund：商城订单分佣扣款 purchase_rebate_refund：采购订单分佣扣款
enum CommissionType {
  purchase_order_payment = 'purchase_order_payment',
  shop_order_payment = 'shop_order_payment',
  shop_rebate_refund = 'shop_rebate_refund',
  purchase_rebate_refund = 'purchase_rebate_refund'
}
enum CommissionTypeName {
  purchase_order_payment = '采购订单分佣',
  shop_order_payment = '店铺订单分佣',
  shop_rebate_refund = '店铺退货退款分佣',
  purchase_rebate_refund = '采购退货退款分佣'
}

enum OrderStatusEnum {
  UNPAID = 0,
  UNDELIVERED = 10,
  DELIVERED = 20,
  COMPLETED = 30,
  CANCELED = 40
}
for (const key in OrderStatusEnum) {
  OrderStatusEnum[ OrderStatusEnum[key]] = key
}
enum OrderStatusEnumName {
  UNPAID = '待支付',
  UNDELIVERED = '待发货',
  DELIVERED = '已发货',
  COMPLETED = '已完成',
  CANCELED = '已取消'
}
// enum OrderTypeName {
//   // 订单类型名称

// }
interface SpanMethodProps {
  row: TradeOrderApi.OrderItemRespVO
  column: TableColumnCtx<TradeOrderApi.OrderItemRespVO>
  rowIndex: number
  columnIndex: number
}

type spanMethodResp = number[] | { rowspan: number; colspan: number } | undefined
const spanMethod = ({ row, rowIndex, columnIndex }: SpanMethodProps): spanMethodResp => {
  // 简化逻辑，确保所有列都能显示
  // 收货人(1)、实付金额(2)、买家留言(3)、操作(4) 这些列需要合并
  const colIndex = [1, 2, 3, 4]
  if (colIndex.includes(columnIndex)) {
    // 只在第一行显示，其他行隐藏
    if (rowIndex !== 0) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
    // 第一行合并所有行
    return {
      rowspan: 1,
      colspan: 1
    }
  }
  return undefined
}

/** 解决 ref 在 v-for 中的获取问题*/
const setOrderTableRef = (el: TableInstance) => {
  if (!el) return
  // 只要第一个表也就是开始的第一行
  if (el.tableId !== 'el-table_2') {
    return
  }
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}
</script>
<style lang="scss" scoped>
:deep(.order-table-col > .cell) {
  padding: 0;
}
</style>
